<template>
  <div class="box">
    <div class="pdf-container">
      <div class="topicBox" v-for="item in testQuestionsInFo">
        <div class="topicTop">
          <div class="bigTopInFo">
            <span>{{ item.name }}</span>
            <span>(共</span>
            <span>{{ item.xiao.length }}题</span>
            <span>)</span>
          </div>
        </div>
        <div class="topicBottom">
          <div class="topicBottomContent">
            <div>
              <div
                v-for="xiao in item.xiao"
                class="xiaoItem"
                :id="item.sort + xiao.sort"
              >
                <div class="xiaoInFo">
                  <span>
                    {{ xiao.sort }}.{{ xiao.itemInfo.questionTypes }}
                  </span>
                  <div style="display: flex; align-items: center"></div>
                </div>
                <div class="xiaoContent">
                  <!-- 单选 -->
                  <template v-if="xiao.itemInfo.questionTypes == '单选题'">
                    <div
                      class="xiaoStem"
                      v-html="setContent(gogo(xiao.itemInfo.testItemContent))"
                    ></div>
                    <div class="xiaoOption">
                      <div
                        class="xiaoOptionItem"
                        v-for="option in xiao.itemInfo.answerList"
                      >
                        <el-radio
                          style="display: none"
                          v-model="xiao.itemInfo.answerJ[0]"
                          :label="option.identifier"
                          disabled
                          >{{ option.identifier }}</el-radio
                        ><span style="padding-left: 20px">{{
                          option.identifier
                        }}</span>
                        <div class="optionInput">
                          <div v-html="option.answerContent"></div>
                        </div>
                      </div>
                    </div>
                    <div class="analysisBox">
                      <div class="analyTitle">解析详情</div>
                      <div
                        class="anlysisHtml"
                        v-html="setContent(gogo(xiao.itemInfo.analysis))"
                      ></div>
                    </div>
                  </template>
                  <!-- 单选 -->
                  <!-- 多选 -->
                  <template v-if="xiao.itemInfo.questionTypes == '多选题'">
                    <div
                      class="xiaoStem"
                      v-html="setContent(gogo(xiao.itemInfo.testItemContent))"
                    ></div>
                    <div class="xiaoOption">
                      <div
                        class="xiaoOptionItem"
                        v-for="option in xiao.itemInfo.answerList"
                      >
                        <el-checkbox
                          style="display: none"
                          :label="option.identifier"
                          disabled
                          :checked="
                            xiao.itemInfo.answerJ.includes(option.identifier)
                          "
                          >{{ option.identifier }}</el-checkbox
                        ><span style="padding-left: 20px">{{
                          option.identifier
                        }}</span>
                        <div class="optionInput">
                          <div v-html="option.answerContent"></div>
                        </div>
                      </div>
                    </div>
                    <div class="analysisBox" style="display: none">
                      <div class="analyTitle">解析详情</div>
                      <div
                        class="anlysisHtml"
                        v-html="setContent(gogo(xiao.itemInfo.analysis))"
                      ></div>
                    </div>
                  </template>
                  <!-- 多选 -->
                  <!-- 判断 -->
                  <template v-if="xiao.itemInfo.questionTypes == '判断题'">
                    <div
                      class="xiaoStem"
                      v-html="setContent(gogo(xiao.itemInfo.testItemContent))"
                    ></div>
                    <div class="xiaoOption" style="margin: 15px 0">
                      <el-radio label="1">正确</el-radio>
                      <el-radio label="2">错误</el-radio>
                    </div>
                    <div class="analysisBox" style="display: none">
                      <div class="analyTitle">解析详情</div>
                      <div
                        class="anlysisHtml"
                        v-html="setContent(gogo(xiao.itemInfo.analysis))"
                      ></div>
                    </div>
                  </template>
                  <!-- 判断 -->
                  <!-- 应用 -->
                  <template v-if="xiao.itemInfo.questionTypes == '应用题'">
                    <div
                      class="xiaoStem"
                      v-html="setContent(gogo(xiao.itemInfo.testItemContent))"
                    ></div>
                    <div class="analysisBox" style="display: none">
                      <div class="analyTitle">解析详情</div>
                      <div
                        class="anlysisHtml"
                        v-html="setContent(gogo(xiao.itemInfo.analysis))"
                      ></div>
                    </div>
                  </template>
                  <!-- 应用 -->
                  <!-- 填空 -->
                  <template v-if="xiao.itemInfo.questionTypes == '填空题'">
                    <div
                      class="xiaoStem"
                      v-html="setContent(gogo(xiao.itemInfo.testItemContent))"
                    ></div>
                    <div class="xiaoOption">
                      <div
                        class="xiaoOptionItem"
                        v-for="option in xiao.itemInfo.answerList"
                      >
                        <div class="optionInput">
                          <div v-html="option.answerContent"></div>
                        </div>
                      </div>
                    </div>
                    <div class="analysisBox" style="display: none">
                      <div class="analyTitle">解析详情</div>
                      <div
                        class="anlysisHtml"
                        v-html="setContent(gogo(xiao.itemInfo.analysis))"
                      ></div>
                    </div>
                  </template>
                  <!-- 填空 -->
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { getSummary } from "../../api/examPaperLibrary";
import { exportPDF } from "@/utils/htmlToPdf.js";
import docx from "html-docx-js/dist/html-docx";
export default {
  data() {
    return {
      testQuestionsInFo: [],
      id: "",
    };
  },
  mounted() {
    if (this.id != "") {
      this.getTestPaperDetail(this.id);
    } else {
      this.getTestPaperDetail(this.$route.query.examinationPaperSummaryId);
    }
    this.startCountdown(3599);
  },
  updated() {
    //判断是否初始配置，若无则配置。
    if (!this.mathJax.isMathjaxConfig.bool) {
      this.mathJax.initMathjaxConfig();
    }
    this.$nextTick((_) => {
      //传入组件id，让组件被MathJax渲染
      this.mathJax.MathQueue("questionList-page");
    });
  },
  methods: {
    //获取试卷详情(回显)
    getTestPaperDetail(val) {
      getSummary(val).then((res) => {
        if (res.code == 200) {
          let obj = JSON.parse(JSON.stringify(res.data));
          delete obj.examinationPaperDetailsList;
          console.log(obj);
          this.form = obj;

          const transformedData = res.data.examinationPaperDetailsList.reduce(
            (accumulator, currentValue) => {
              // 查找是否已有相应的题号（name1）在累积器中
              const existingItem = accumulator.find(
                (item) => item.name === currentValue.bigProblem
              );
              if (existingItem) {
                // 如果找到，则向xiao数组中添加当前小题对象
                let xiaoObj = {
                  xName: currentValue.questions,
                  itemBankId: currentValue.itemBankId,
                  itemInfo: currentValue.itemBank,
                  fenzhi: currentValue.score,
                  fenzhiIsNull: false,
                  sort: currentValue.questions.split(".")[0],
                };
                existingItem.xiao.push(xiaoObj);
              } else {
                // 如果没有找到，则创建一个新对象，并初始化xiao数组

                let digQu = {
                  name: currentValue.bigProblem,
                  sort: currentValue.reserve1,
                  fenzhi: 0,
                  xiao: [
                    {
                      xName: currentValue.questions,
                      itemBankId: currentValue.itemBankId,
                      itemInfo: currentValue.itemBank,
                      fenzhi: currentValue.score,
                      fenzhiIsNull: false,
                      sort: currentValue.questions.split(".")[0],
                    },
                  ],
                };

                accumulator.push(digQu);
              }

              // 返回累积器以便进行下一次迭代
              return accumulator;
            },
            []
          ); // 初始值为空数组
          console.log(transformedData);
          // this.testQuestionsInFo = transformedData;
          this.$set(this, "testQuestionsInFo", transformedData);
        }
      });
    },

    //倒计时
    startCountdown(seconds) {
      function bu(val) {
        if (val < 10) {
          return `0${val}`;
        } else {
          return val;
        }
      }
      this.intervalId = setInterval(() => {
        this.hours = bu(Math.floor(seconds / 3600));
        this.minutes = bu(Math.floor((seconds % 3600) / 60));
        this.remainingSeconds = bu(seconds % 60);

        if (seconds <= 0) {
          clearInterval(this.intervalId);
          countdownElement.textContent = "倒计时结束!";
        } else {
          seconds--;
        }
      }, 1000);
    },
    //每个大题的总分
    setFenzhi(n) {
      // console.log(n,this);
      let amount = 0;
      n.xiao.forEach((ele) => {
        amount += Number(ele.fenzhi);
      });
      return amount;
    },
    scrollToElement(elementId) {
      var element = document.getElementById(elementId);
      if (element) {
        element.scrollIntoView({ behavior: "smooth" }); // 平滑滚动
      }
    },
    //导出pdf------ 数据统计汇总为导出文件名称；my_table_1为要导出的dom元素id
    exportData() {
      console.log(this.form.examinationPaperSummaryName);
      this.pdfDy = true;
      exportPDF(this.form.examinationPaperSummaryName, "pdfDom");
    },

    exportToWord(elementId) {
      const content = this.$refs[elementId]; // 获取div元素，或者通过Vue的ref来获取
      console.log(content);
      const converted = docx.asBlob(content.outerHTML, {
        orientation: "portrait",
        margins: { top: 720 },
      });

      // 创建下载链接
      const downloadLink = document.createElement("a");
      downloadLink.href = URL.createObjectURL(converted);
      downloadLink.download = "document.docx";

      // 触发下载
      downloadLink.click();
    },

    //img去除\\
    setContent(val) {
      if (val.includes('\\\\"')) {
        let abc = val.replaceAll('\\\\"', "");
        return abc;
      } else {
        let abc = val.replaceAll('\\"', "");
        return abc;
      }
    },

    gogo(val) {
      // console.log(val);
      if (val == "" || val == null) return;
      let item = JSON.parse(JSON.stringify(val));
      let ord = /begin{array}([\s\S]*?)\\end{array}/g; // 定义正则表达式，用于匹配以 [\begin{array} 开头的字符串

      let arr = item.match(ord); // 使用 match 方法获取所有匹配项
      // console.log(arr, "arr");
      if (arr == null || arr.length == 0) return val;

      let deleP = (P) => {
        let newP = P.split("<p>");

        let a = newP.join(" ");
        let b = a.split("</p>");
        let c = b.join(" ");
        // console.log(c, "newp");
        return c;
      };

      let abc = null;
      arr.forEach((ele) => {
        abc = val.split(ele);
        abc = abc.join(deleP(ele));
      });
      return abc;
      console.log(abc, "拼接完成");
    },
  },
};
</script>
<style lang="scss" scoped>
.box {
  padding: 20px;
  background-color: #f1f3f8;
  .pdf-container {
    /* width: 210mm; */
    background-color: white;
  }
}

.xiaoItem {
  height: 279mm;
}
</style>
